<?php
$db=pg_connect("host=localhost port=5432 dbname=sms user=postgres password=binhminh");

$result=pg_query($db,"select * from out_status()");
$status = pg_fetch_result($result, 0, 0);
if($status == 't'){
    $result=pg_query($db,"select * from in_status()");
    $status = pg_fetch_result($result, 0, 0);
	$signal = 'CHECK ' . rand();
    pg_query_params($db,"select * from out_insert($1, $2, $3)",array('84905000706', $signal, 'CHECK'));	
    if($status == 't'){
		pg_query_params($db,"update status set signal = $1",array($signal));
    }
    else{
		pg_query_params($db,"update status set signal = $1, count = count + 1",array($signal));
        // Bao dau vao khong nhan tin nhan
		$count = pg_fetch_result($result, 0, 1);
        pg_query_params($db,"select * from out_insert($1, $2, $3)",array('84905154030', 'SCTV SMS: khong nhan duoc tin ve: ' . $count, 'CHECK'));
    }
}
else{
    // Gui tin nhan bao dau ra khong duoc
    /*
    require_once('PhpSerial.php');
    $PhpSerial=new PhpSerial;
    $PhpSerial->deviceSet('COM3');
    echo 'gui0';
    if($PhpSerial->deviceOpen()){
        echo 'gui1';
        $PhpSerial->sendMessage("AT\r");
        $PhpSerial->sendMessage("AT+CMGF=1\n");
        $out=$PhpSerial->readPort();
        echo $out;
        if(strpos($out,"OK")!==false){
            echo 'gui2';
            $PhpSerial->sendMessage('AT+CMGS="0905154030"\n\r');
            $out=$PhpSerial->readPort();
            echo $out;
            $PhpSerial->sendMessage('SCTV SMS: khong gui duoc tin nhan di\x1a\n\r');
            //$PhpSerial->sendMessage(chr(26));
        }
    }
    $PhpSerial->deviceClose();
    */
}
pg_close($db);
?>